package com.fanketly.funacg2

import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DrawerState
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalDrawerSheet
import androidx.compose.material3.ModalNavigationDrawer
import androidx.compose.material3.NavigationDrawerItem
import androidx.compose.material3.NavigationDrawerItemDefaults
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberDrawerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavHostController
import com.fanketly.funacg2.data.network.RetrofitNetwork
import com.fanketly.funacg2.ui.navigation.DrawerDestination
import com.fanketly.funacg2.ui.screen.NavGraphs
import com.fanketly.funacg2.ui.screen.destinations.DetailDestination
import com.fanketly.funacg2.ui.screen.destinations.LoginScreenDestination
import com.fanketly.funacg2.ui.screen.destinations.TagsScreenDestination
import com.fanketly.funacg2.ui.theme.FunACG2Theme
import com.fanketly.funacg2.ui.viewmodels.GlobalStates
import com.fanketly.funacg2.ui.viewmodels.HomeViewModel
import com.fanketly.funacg2.ui.viewmodels.MusicViewModel
import com.fanketly.funacg2.ui.viewmodels.TagViewModel
import com.fanketly.funacg2.ui.viewmodels.state.GlobalState
import com.fanketly.funacg2.utils.ToastUtils
import com.lzx.starrysky.StarrySky
import com.lzx.starrysky.manager.PlaybackStage
import com.ramcosta.composedestinations.DestinationsNavHost
import com.ramcosta.composedestinations.navigation.dependency
import com.ramcosta.composedestinations.navigation.navigate
import com.ramcosta.composedestinations.navigation.popUpTo
import com.ramcosta.composedestinations.rememberNavHostEngine
import com.ramcosta.composedestinations.spec.DirectionDestinationSpec
import com.ramcosta.composedestinations.spec.NavHostEngine
import com.ramcosta.composedestinations.utils.currentDestinationFlow
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import javax.inject.Inject

@AndroidEntryPoint
class MainActivity : ComponentActivity() {

    private val musicViewModel by viewModels<MusicViewModel>()
    private val homeViewModel: HomeViewModel by viewModels()
    private val tagViewModel: TagViewModel by viewModels()


    @Inject
    lateinit var retrofitNetwork: RetrofitNetwork

    @Inject
    lateinit var globalStates: GlobalStates

    private val drawerList by lazy {
        mutableListOf(
            DrawerDestination.Home,
            DrawerDestination.Search,
            DrawerDestination.Tags,
            DrawerDestination.Recommend,
            DrawerDestination.Favourite,
            DrawerDestination.History,
            DrawerDestination.Setting,
        )
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        homeViewModel.isExpires()//判断token是否过期，过期就自动登录
        setView()
    }


    private fun setView() {
        val drawerDestinationList = drawerList.map { it.direction }
        setContent {
            FunACG2Theme(dynamicColor = false) {
                //侧滑
                val drawerState = rememberDrawerState(DrawerValue.Closed)
                val scope = rememberCoroutineScope()
//                var selectedItem by remember { mutableIntStateOf(0) }
                //导航
                val rememberNavHostEngine = rememberNavHostEngine()
                val rememberNavController = rememberNavHostEngine.rememberNavController()
                MainLayout(
                    rememberNavHostEngine,
                    rememberNavController,
                    drawerState,
                    drawerList,
                    drawerDestinationList,
                    musicViewModel, homeViewModel, tagViewModel
                )

//                LaunchedEffect(key1 = globalStates.globalUiState, block = {
//                    if (globalStates.globalUiState is GlobalState.ToDetail) {
//                        Log.i("TAG", "setView: " + globalStates.globalUiState)
//                        rememberNavController.navigate(DetailDestination)
//                    }
//                })
                GlobalState(
                    globalStates.globalUiState,
                    toDetail = { rememberNavController.navigate(DetailDestination) },
                    openDrawer = { scope.launch { drawerState.open() } },
                    onClose = globalStates::setStateClose,
                    onReload = {
                        // TODO:
                        rememberNavController.navigate(LoginScreenDestination)
//                        homeViewModel::reload
                    }
                )
            }
        }
    }

    override fun onStart() {
        super.onStart()
        App.sServiceConnect.observe(this) {
            if (it) {
                setPlaybackState()
            }
        }
    }

    private fun setPlaybackState() {
        StarrySky.with().playbackState().observe(this) { stage ->
            musicViewModel.apply {
                when (stage.stage) {
                    PlaybackStage.ERROR -> {
                        ToastUtils.shortToast("播放错误")
                    }

                    PlaybackStage.PLAYING -> {
                        _isPlaying.value = true
                        stage.songInfo?.let {
                            _audioInfo.value = it
                            _audioAllTime.value = (StarrySky.with().getDuration() / 1000).toInt()
                        }
                        setOnPlayProgressListener()
                    }

                    PlaybackStage.PAUSE -> {
                        _isPlaying.value = false
                    }

                    PlaybackStage.IDLE -> {
                        _isPlaying.value = false
                        _audioProcess.value = 0
                    }
                }
            }
        }
    }

}

@Composable
fun MainLayout(
    rememberNavHostEngine: NavHostEngine,
    rememberNavController: NavHostController,
    drawerState: DrawerState,
    drawerList: MutableList<DrawerDestination>,
    drawerDestinationList: List<DirectionDestinationSpec>,
    musicViewModel: MusicViewModel,
    homeViewModel: HomeViewModel,
    tagViewModel: TagViewModel,
) {
    val currentDestination by rememberNavController.currentDestinationFlow.collectAsStateWithLifecycle(
        initialValue = NavGraphs.root.startRoute
    )
    val scope = rememberCoroutineScope()
    ModalNavigationDrawer(drawerState = drawerState,
        gesturesEnabled = currentDestination in drawerDestinationList,
        modifier = Modifier.background(MaterialTheme.colorScheme.background),
        drawerContent = {
            ModalDrawerSheet {
                Spacer(Modifier.height(12.dp))
                NavigationDrawerItem(
                    icon = {
                        Icon(
                            if (App.isLogin()) DrawerDestination.Logout.icon else DrawerDestination.Login.icon,
                            contentDescription = null
                        )
                    },
                    label = { Text(stringResource(id = if (App.isLogin()) DrawerDestination.Logout.label else DrawerDestination.Login.label)) },
                    selected = false,
                    onClick = {
                        scope.launch {
//                                            selectedItem = index
                            drawerState.close()
                            if (App.isLogin()) App.logout() else rememberNavController.navigate(
                                LoginScreenDestination
                            )
                        }
                    },
                    modifier = Modifier.padding(NavigationDrawerItemDefaults.ItemPadding)
                )
                drawerList.forEachIndexed { index, item ->
                    NavigationDrawerItem(
                        icon = {
                            Icon(
                                item.icon, contentDescription = null
                            )
                        },
                        label = { Text(stringResource(id = item.label)) },
                        selected = item.direction == currentDestination,
                        onClick = {
                            if (currentDestination == item.direction) return@NavigationDrawerItem
                            scope.launch {
//                                            selectedItem = index
                                drawerState.close()
                                rememberNavController.navigate(item.direction) {
                                    popUpTo(NavGraphs.root) {
//                                        saveState = true//保存状态
                                    }
                                    launchSingleTop = true
//                                    restoreState = true//恢复状态
                                }
                            }
                        },
                        modifier = Modifier.padding(NavigationDrawerItemDefaults.ItemPadding)
                    )
                }
            }
        }) {
        DestinationsNavHost(navGraph = NavGraphs.root,
            engine = rememberNavHostEngine,
            navController = rememberNavController,
            dependenciesContainerBuilder = {
                dependency(homeViewModel)
                dependency(musicViewModel)
                dependency(TagsScreenDestination) {
                    tagViewModel
                }
//                            dependency(DetailDestination) {
//                                hiltViewModel<FavouriteViewModel>(this@MainActivity)
//                            }
//                            dependency(FavouriteScreenDestination) {
//                                hiltViewModel<FavouriteViewModel>(this@MainActivity)
//                            }
//                                    dependency(DetailDestination, dependencyProvider = {
//                                        {
//                                            destinationsNavigator.popBackStack()
//                                            Unit
//                                        }
//                                    })
            })
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun GlobalState(
    state: GlobalState,
    toDetail: () -> Unit,
    openDrawer: () -> Unit,
    onClose: () -> Unit,
    onReload: () -> Unit,
) {
    Log.i("TAG", "GlobalState: $state")
    when (state) {
        is GlobalState.ShowToast -> {
            ToastUtils.shortToast(state.message)
            onClose()
        }

        GlobalState.Loading -> {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .combinedClickable(indication = null,
                        interactionSource = remember { MutableInteractionSource() },
                        role = Role.Image,
                        onClick = { }), contentAlignment = Alignment.Center
            ) {
                CircularProgressIndicator()
            }
        }

        GlobalState.NotAuthorization -> {
            AlertDialog(onDismissRequest = { onClose() }, confirmButton = {
                TextButton(onClick = { onReload() }) {
                    Text(text = stringResource(id = R.string.confirm))
                }
            }, text = { Text(text = stringResource(id = R.string.not_authorization)) })
        }

        GlobalState.Close -> {
        }

        is GlobalState.ToDetail -> {
            toDetail()
        }

        GlobalState.OpenDrawer -> {
            openDrawer()
            onClose()
        }
    }
}


@Preview
@Composable
private fun Preview() {
    FunACG2Theme {
        Surface {
//            GlobalState(state = GlobalState.NotAuthorization, onClose = { }) {
//
//            }
        }
    }
}
